<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="120px">
      <el-form-item label="礼物模板名称" prop="templateName">
        <el-input
          v-model="queryParams.templateName"
          placeholder="请输入礼物模板名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!--<el-form-item label="创建人" prop="createdBy">-->
        <!--<el-input-->
          <!--v-model="queryParams.createdBy"-->
          <!--placeholder="请输入创建人"-->
          <!--clearable-->
          <!--size="small"-->
          <!--@keyup.enter.native="handleQuery"-->
        <!--/>-->
      <!--</el-form-item>-->
      <!--<el-form-item label="创建时间" prop="createdTime">-->
        <!--<el-date-picker clearable size="small" style="width: 200px"-->
          <!--v-model="queryParams.createdTime"-->
          <!--type="date"-->
          <!--value-format="yyyy-MM-dd"-->
          <!--placeholder="选择创建时间">-->
        <!--</el-date-picker>-->
      <!--</el-form-item>-->
      <!--<el-form-item label="更新人" prop="lastUpdatedBy">-->
        <!--<el-input-->
          <!--v-model="queryParams.lastUpdatedBy"-->
          <!--placeholder="请输入更新人"-->
          <!--clearable-->
          <!--size="small"-->
          <!--@keyup.enter.native="handleQuery"-->
        <!--/>-->
      <!--</el-form-item>-->
      <!--<el-form-item label="更新时间" prop="lastUpdatedTime">-->
        <!--<el-date-picker clearable size="small" style="width: 200px"-->
          <!--v-model="queryParams.lastUpdatedTime"-->
          <!--type="date"-->
          <!--value-format="yyyy-MM-dd"-->
          <!--placeholder="选择更新时间">-->
        <!--</el-date-picker>-->
      <!--</el-form-item>-->
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['ymx:ymxtemplateInfo:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['ymx:ymxtemplateInfo:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['ymx:ymxtemplateInfo:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-upload2"
          size="mini"
          @click="excelUploadModal = true"
        >导入</el-button>

      </el-col>
      <!--<el-col :span="1.5">-->
        <!--<el-button-->
          <!--type="warning"-->
          <!--icon="el-icon-download"-->
          <!--size="mini"-->
          <!--@click="handleExport"-->
          <!--v-hasPermi="['ymx:ymxtemplateInfo:export']"-->
        <!--&gt;导出</el-button>-->
      <!--</el-col>-->
	  <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="ymxtemplateInfoList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="礼物模板表主键" align="center" prop="templateId" /> -->
      <el-table-column label="礼物模板名称" align="center" prop="templateName" width="180" show-overflow-tooltip />
      <!--<el-table-column label="创建人" align="center" prop="createdBy" />-->
      <el-table-column label="礼物图片" align="center" prop="giftInfoList">
        <template slot-scope="scope">
          <div>
            <img v-for="(item, index) in scope.row.giftInfoList" :key="index" :src="item.giftImage"
            style="max-width: 120px;margin: 5px; max-height: 200px;float:left;padding:5px;background:#ccc" :title="item.giftName">
          </div>
        </template>
      </el-table-column>
      <!-- <el-table-column label="更新人" align="center" prop="lastUpdatedBy" />
      <el-table-column label="更新时间" align="center" prop="lastUpdatedTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.lastUpdatedTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column> -->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="180" >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['ymx:ymxtemplateInfo:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['ymx:ymxtemplateInfo:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改礼物模板对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="礼物模板名称" prop="templateName">
          <el-input v-model="form.templateName" placeholder="请输入礼物模板名称" />
        </el-form-item>
        <el-form-item label="模板类型" prop="templateType">
          <el-radio-group v-model="form.templateType">
            <el-radio :label="3">外链</el-radio>
            <el-radio :label="6">附件</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="图片">
          <div v-if="form.templateType === 3">
            图片名称：
            <el-input placeholder="请输入图片名称" v-model="imageData.giftName"></el-input>
            图片地址：
            <el-input placeholder="请输入图片地址" v-model="imageData.giftImage">
              <el-button slot="append" icon="el-icon-plus" @click="addImage"></el-button>
            </el-input>
          </div>
          <div v-else>
            图片名称：
            <el-input placeholder="请输入图片名称" v-model="imageData.giftName">
              <el-button slot="append" icon="el-icon-plus" @click="addImage"></el-button></el-input>
            上传图片：
            <div class="uploadBox">
              <input type="file" @change="uploadFile">
              <span v-if="isTest"></span>
              <img v-if="imageData.giftImage" v-lazy="imageData.giftImage" :key="imageData.giftImage" :src="imageData.giftImage" alt="">
              <i v-else slot="default" class="el-icon-plus"></i>
            </div>
          </div>
        </el-form-item>
        <!-- <List>
          <ListItem v-for="(item,index) in imageList" :key="index">
              <ListItemMeta :avatar="item.giftImage" :title="item.giftName" />
          </ListItem>
        </List> -->
        <div class="imageList">
          <div class="imageList-item" v-for="(item,index) in imageList" :key="index">
            <p>{{item.giftName}}</p>
              <!-- style="width: 100px; height: 100px" -->
            <el-image
              :src="item.giftImage"
              style="max-height: 300px"
              :preview-src-list="[item.giftImage]">
            </el-image>
            <el-button type="primary" style="width: 100%" @click="delImage(index)">删除</el-button>
          </div>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="导入" :visible.sync="excelUploadModal" width="400px" append-to-body>
      <p>附件：<el-button type="primary" @click="downTemplate">下载模板</el-button></p>
      <el-upload
        class="upload-demo"
        style="width: 100%"
        :headers="headers"
        :data="{updateSupport:1}"
        :show-file-list="false"
        :on-success="onSuccess"
        drag
        :action="`${baseURL}/ymx/ymxtemplateInfo/importDataGift`"
        multiple>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="cancelExcelModal">确 定</el-button>
        <el-button @click="cancelExcelModal">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import baseURL from '@/utils/requestUrl'
import { listYmxtemplateInfo, getYmxtemplateInfo, delYmxtemplateInfo, addYmxtemplateInfo, updateYmxtemplateInfo, exportYmxtemplateInfo } from "@/api/ymx/ymxtemplateInfo";
import axios from 'axios'
import { getToken } from '@/utils/auth'
export default {
  name: "YmxtemplateInfo",
  data() {
    return {
      baseURL: baseURL,
      excelUploadModal: false,
      headers: {
        Authorization: ''
      },
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      isTest: false,
      // 总条数
      total: 0,
      imageData: {
        giftImage: '',
        giftName: ''
      },
      // 礼物模板表格数据
      ymxtemplateInfoList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        templateName: null,
        createdBy: null,
        createdTime: null,
        lastUpdatedBy: null,
        lastUpdatedTime: null
      },
      // 表单参数
      form: {},
      imageList: [],
      // 表单校验
      rules: {
        templateName: [
          { required: true, message: "礼物模板名称不能为空", trigger: "blur" }
        ],
        templateType:[
          { required: true, message: "模板类型不能为空", trigger: "change" }
        ],
      }
    };
  },
  created() {
    this.headers.Authorization = 'Bearer ' + getToken();
    this.getList();
  },
  methods: {
    /** 查询礼物模板列表 */
    getList() {
      this.loading = true;
      listYmxtemplateInfo(this.queryParams).then(response => {
        this.ymxtemplateInfoList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    cancelExcelModal() {
      this.excelUploadModal = false;
    },
    onSuccess(res, file) {
      if (res.code === 200) {
        this.$message({ message: '导入成功', type: 'success'});
      } else {
        file.status = 'error'
        console.log(file)
        this.$message({ message: res.msg, type: 'error'});
      }
      console.log(res)
    },
    downTemplate() {
      window.open(baseURL + "/profile/upload/%E7%A4%BC%E7%89%A9%E6%A8%A1%E6%9D%BF.xlsx")
    },
    uploadFile(e) {
        this.imageData.giftImage = '';
        let file = e.target.files[0];
        var formData = new FormData();
        formData.append('file',file);
        axios.post(baseURL + '/common/upload', formData).then(res => {
            if (res.data.code === 200) {
              this.$set(this.imageData, 'giftImage', res.data.url)
                this.imageData.giftImage = res.data.url;
                this.isTest = !this.isTest;
                this.$message({ message: '上传成功', type: 'success'});
                // return
                // this.$router.push({path:'/gift', query: {customerInformationId: this.orderData.customerInformationId, asin: this.orderData.asin, orderId: this.orderData.orderId}})
            } else {
                this.$message({ message: '上传失败', type: 'error'});
            }
        })
    },
    delImage(index) {
      this.imageList.splice(index, 1);
    },
    addImage() {
      if (this.imageList.length == 6) {
        this.$message({
          message: '礼物最多为六个',
          type: 'warning'
        });
        return
      }
      if (!this.imageData.giftName || !this.imageData.giftImage) {
        this.$message({
          message: '图片名称与地址为必填项',
          type: 'warning'
        });
        return
      }
      let imageData = JSON.parse(JSON.stringify(this.imageData))
      this.imageList.push(imageData);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.imageList = [];
      this.imageData = {}
      this.form = {
        templateId: null,
        templateName: null,
        createdBy: null,
        createdTime: null,
        lastUpdatedBy: null,
        lastUpdatedTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.templateId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加礼物模板";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const templateId = row.templateId || this.ids
      getYmxtemplateInfo(templateId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改礼物模板";
        this.imageList =  row.giftInfoList || []
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.giftInfoList = this.imageList;
          if (this.form.templateId != null) {
            updateYmxtemplateInfo(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }
            });
          } else {
            addYmxtemplateInfo(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const templateIds = row.templateId || this.ids;
      this.$confirm('是否确认删除礼物模板编号为"' + templateIds + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delYmxtemplateInfo(templateIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function() {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有礼物模板数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportYmxtemplateInfo(queryParams);
        }).then(response => {
          this.download(response.msg);
        }).catch(function() {});
    }
  }
};
</script>

<style scoped>
.imageList{
  overflow: hidden;
}
.imageList-item{
  float: left;
  width: 200px;
  /* max-height: 240px; */
  padding: 5px;
  border: 1px solid #d1d1d1;
  border-radius: 4px;
  margin: 5px;
  overflow: hidden;
}
.imageList-item image{
  width: 100%;
  max-height: 150px;
}
.imageList-item p{
  width: 100%;
  overflow: hidden;
  text-overflow:ellipsis;
  white-space: nowrap;
}

.uploadBox{
  width: 200px;
  height: 200px;
  border: 1px solid #ccc;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 38px;
  border-radius: 4px;
  position: relative;
  overflow: hidden;
}
.uploadBox input{
  position: absolute;
  width: 100%;
  height: 100%;
  left: 0;
  top: 0;
  opacity: 0;
  cursor: pointer;
}
.uploadBox img{
  width: 98%;
  max-height: 300px;
}
</style>
